/* 一个简单的闹钟程序,智谱清言写的ahk 1.0版本,我改写成2.0

  By setycyas @2025-02-04
*/

class alarm {
  
  ; 初始化变量
  alarmSet := false
  alarmTime := ""
  timer := ""
  _gui := "" ;窗口,以下为组建
  btnSet := ""
  btnCancel := ""
  editTime := ""
  statusBar := ""
  
  __New(){
    this._gui := Gui("-MaximizeBox +MinimizeBox", "闹钟")
    this._gui.Add("Text", "", "设置闹钟时间 (格式 HH:MM:SS):")
    this.editTime := this._gui.Add("Edit", "yp+20", A_Hour . ":" . A_Min . ":" . A_Sec)
    this.btnSet := this._gui.Add("Button", "yp+30", "设置")
    this.btnCancel := this._gui.Add("Button", "xp+50", "取消")
    this.statusBar := this._gui.Add("StatusBar",, "状态栏")
    this.timer := ObjBindMethod(this, "alarmTimer")
  }
  
  /** 事件绑定函数
  */
  ;关闭窗口时退出
  onGuiClose(thisGui){
    ExitApp()
  }
  ;设置按钮
  onBtnSetClick(obj, info){
    local splitTime, targetTime, currentTime, timeToWait
    ;已设定的情况
    if this.alarmSet {
      this.statusBar.SetText("已设置,请取消再重设")
      return
    }
    ;时间格式不对的情况
    If (not RegExMatch(this.editTime.Text, "^\d{1,2}:\d{1,2}:\d{1,2}$")){
      this.statusBar.SetText("时间格式不正确请使用HH:MM:SS")
      return
    }
    ;计算时间设定timer
    splitTime := StrSplit(this.editTime.Text, ":")
    targetTime := (SplitTime[1]*3600) + (SplitTime[2]*60) + SplitTime[3]
    currentTime := (A_Hour*3600) + (A_Min*60) + A_Sec
    if (targetTime < currentTime) {
      targetTime += 24*3600 ; 如果设置的时间已经过去，则加一天
    }
    timeToWait := targetTime - currentTime
    SetTimer(this.timer, timeToWait*(-1000)) ;负数,表示只执行一次
    this.alarmSet := true
    this.alarmTime := this.editTime.Text
    this.statusBar.SetText("已设置闹钟:" . SplitTime[1] . "时" . SplitTime[2] . "分" . SplitTime[3] . "秒")
  }
  ;取消按钮
  onBtnCancelClick(obj, info){
    ;未设定的情况
    if not this.alarmSet {
      this.statusBar.SetText("现在没有设定闹钟")
      return
    }
    SetTimer(this.timer, 0) ;0表示删除
    this.alarmSet := false
    this.statusBar.SetText("闹钟已取消")
  }
  
  ;闹钟事件
  alarmTimer(){
    this.statusBar.SetText("闹钟结束")
    Msgbox("到点" . this.alarmTime)
  }
  
  main(){
    static obm := ObjBindMethod ;函数名简写,制作对象绑定函数
    this.btnSet.onEvent("Click",obm(this, "onBtnSetClick"))
    this.btnCancel.onEvent("Click",obm(this, "onBtnCancelClick"))
    this._gui.onEvent("Close",obm(this, "onGuiClose"))
    this._gui.show("w220 h150")
  }
  
}

alarm().main()
